<script setup lang="ts">
import { inject, ref, watchEffect } from 'vue'
import { NSpin, useThemeVars } from 'naive-ui'
import { findChildrenByName } from '@/router/utils'
import { useTabsStore } from '@/stores/modules/tabs'
import { useRoute, RouterView } from 'vue-router'
import { storeToRefs } from 'pinia'
import type { lockState } from '@/types/stores/tabs'
import { baseRoutes } from '@/router/route'
type PropsState = {
  superiorName: string
}
const props = withDefaults(defineProps<PropsState>(), {
  superiorName: ''
})
const $clone = inject('$clone') as <T>(data: T) => T
const route: any = useRoute()
const tabsStore = useTabsStore()
const themeVars = useThemeVars()
const { getVisitedRoutes: visitedRoutes, getLocaks: locks } =
  storeToRefs(tabsStore)
const routerKey = ref()
const keepList = ref([])
watchEffect(() => {
  const matched = toRaw(route).matched
  if (matched) {
    const index = matched.findIndex(el => el.name === props.superiorName) + 1
    if (index <= matched.length - 1) {
      routerKey.value = matched[index].path
    }
  } else {
    routerKey.value = '/'
  }
  const arr = $clone(locks.value).map((el: lockState) => {
    return el.childer
  })
  arr.push($clone(visitedRoutes.value))
  const childer: string[] = findChildrenByName(
    baseRoutes,
    props.superiorName
  ).map(el => el.name)
  keepList.value = arr
    .flat()
    .filter(el => childer.includes(el.name))
    .map((el: any) => {
      return el.name
    })
})
</script>
<template>
  <Suspense>
    <template #default>
      <router-view
        v-slot="{ Component }"
        class="router-name"
        :style="{
          '--n-color': themeVars.primaryColor
        }"
      >
        <transition name="slide-right" mode="out-in">
          <keep-alive :include="keepList">
            <component :is="Component" :key="routerKey"></component>
          </keep-alive>
        </transition>
      </router-view>
    </template>
    <template #fallback>
      <div class="flex justify-center pt-[30px]">
        <NSpin size="large" />
      </div>
    </template>
  </Suspense>
</template>

<style lang="scss" scoped>
.router-name {
  box-sizing: border-box;
}
</style>
